# 保存当前工作目录
$originalLocation = Get-Location

# 设置工作目录为脚本所在目录的上一级
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location (Join-Path $scriptPath "..")


# 设置日志文件路径
$errorlog = Join-Path $scriptPath "error_log.txt"

$mainbranch = "master"

function Invoke-Command {
    param (
        [string]$command,
        [string]$action
    )

    try {
        Invoke-Expression $command 2>&1 | Out-File -FilePath $errorlog -Append
        if ($LASTEXITCODE -ne 0) {
            Write-Output "$action failed, check $errorlog for details."
            exit 1
        }else {
            Write-Output "$action successful."
            if (Test-Path $errorlog) {
                Remove-Item $errorlog
            }
        }
    } catch {
        # 捕获异常并将异常信息写入日志文件
        $errorMessage = $_.Exception.Message
        $errorStackTrace = $_.Exception.StackTrace
        $errorDetails = "Action: $action`nError: $errorMessage`nStack Trace: $errorStackTrace"
        # Write-Output "$action failed, check $errorlog for details."
        Write-Output "$errorDetails"
        exit 1
    }
}

# 执行命令
Invoke-Command -command "git add ." -action "add"
Invoke-Command -command "git commit -m 'quick update! no message.'" -action "commit"
Invoke-Command -command "git pull sjy $mainbranch --rebase" -action "pull"
Invoke-Command -command "git push sjy $mainbranch" -action "push"


# 恢复原始工作目录
Set-Location $originalLocation